package 算法.leetcode.offer;


import java.util.HashMap;
import java.util.Map;

/**
 * @author lchenglong
 * @date 2022/4/21
 */
public class Offer35 {

    public static void main(String[] args) {
        Node node7 = new Node(7);
        Node node13 = new Node(13);
        Node node11 = new Node(11);
        Node node10 = new Node(10);
        Node node1 = new Node(1);
        node7.next = node13;
        node13.next = node11;
        node11.next = node10;
        node10.next =node1;
        node7.random = null;
        node13.random = node7;
        node11.random = node1;
        node10.random = node11;
        node1.random = node7;

        Node a = new Node(1);
        Node b = new Node(2);
        a.next = b;
        b.next = null;
        a.random = b;
        b.random = b;
        Offer35 instance = new Offer35();
        Node node = instance.copyRandomList(a);
        System.out.println(1111);
    }
    Map<Node, Node> cachedNode = new HashMap<Node, Node>();

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        // 不存在就新建
        if (!cachedNode.containsKey(head)) {
            Node headNew = new Node(head.data);
            // 提前暴露
            cachedNode.put(head, headNew);
            // 成员变量设置
            headNew.next = copyRandomList(head.next);
            headNew.random = copyRandomList(head.random);
        }
        return cachedNode.get(head);
    }

    public static class Node {
        private Node next;
        private Node random;
        private Integer data;
        private Node(Integer value){
            this.data = value;
        }
    }

}
